package com.sitanyun.merchant.guide.frament.view.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.base.BaseActivity;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.bean.ImageLoadBean;
import com.sitanyun.merchant.guide.bean.MyUserInfoBean;
import com.sitanyun.merchant.guide.bean.WxImagesBean;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.frament.presenter.impl.UserMessageAPresenterImpl;
import com.sitanyun.merchant.guide.frament.presenter.inter.IUserMessageAPresenter;
import com.sitanyun.merchant.guide.frament.view.inter.IUserMessageAView;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.weiht.GlideEngine;
import com.sitanyun.merchant.guide.weiht.ImageLoadUtrils;
import com.sitanyun.merchant.guide.weiht.Loading_view;
import com.sitanyun.merchant.guide.weiht.PictureUtils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 我的信息
 */
public class UserMessageActivity extends BaseActivity implements IUserMessageAView {


    @BindView(R.id.user_herder_image)
    CircleImageView userHerderImage;
    @BindView(R.id.ll_image)
    LinearLayout llImage;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.ll_name)
    LinearLayout llName;
    @BindView(R.id.user_phone)
    TextView userPhone;
    @BindView(R.id.ll_phone)
    LinearLayout llPhone;
    @BindView(R.id.user_wxm)
    TextView userWxm;
    @BindView(R.id.ll_wx)
    LinearLayout llWx;
    @BindView(R.id.user_zy)
    TextView userZy;
    @BindView(R.id.ll_zy)
    LinearLayout llZy;
    @BindView(R.id.user_shop)
    TextView userShop;
    @BindView(R.id.ll_shop)
    LinearLayout llShop;
    @BindView(R.id.user_enter)
    TextView userEnter;
    @BindView(R.id.ll_enter)
    LinearLayout llEnter;
    private IUserMessageAPresenter mIUserMessageAPresenter;
    private MyUserInfoBean myUserInfoBean;
    public static final int RC_CHOOSE_PHOTO = 2;
    private Loading_view loading_view;
    private String TAKE_PHOTO_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
    private String filePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //P层创建关联
        mIUserMessageAPresenter = new UserMessageAPresenterImpl(this);
        //loding
        loading_view = new Loading_view(UserMessageActivity.this, R.style.CustomDialog);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_message;
    }

    /**
     * 显示
     */
    @Override
    protected void onResume() {
        super.onResume();
        //请求数据
        mIUserMessageAPresenter.getuser();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setFindViewById(true);
        setTitleStr("我的信息");
    }

    @Override
    public void initView() {

    }

    @Override
    public <T> T request(int requestFlag) {
        return null;
    }

    @Override
    public <T> void response(T response, int responseFlag) {
        if (responseFlag == IUserMessageAView.RESPONSE_ONE) {
            myUserInfoBean = (MyUserInfoBean) response;
            if (myUserInfoBean.getCode() == 0) {
                userEnter.setText(myUserInfoBean.getData().getEnterprise() + "");
                userZy.setText(myUserInfoBean.getData().getPosition() + "");
                userShop.setText(myUserInfoBean.getData().getStroe() + "");
                Glide.with(UserMessageActivity.this).load(myUserInfoBean.getData()
                        .getHeadUrl()).apply(new RequestOptions().error(R.mipmap.cimg)).into(userHerderImage);
                userName.setText(myUserInfoBean.getData().getName() + "");
                userPhone.setText(myUserInfoBean.getData().getPhone() + "");
                if (myUserInfoBean.getData().getWxEwm() == null) {
                    userWxm.setVisibility(View.VISIBLE);
                } else {
                    userWxm.setVisibility(View.VISIBLE);
                    userWxm.setText("已上传");
                }
            } else {
                ToastUtil.showToast(UserMessageActivity.this, myUserInfoBean.getMsg() + "");
            }
        }
    }

    @OnClick({R.id.ll_image, R.id.ll_name, R.id.ll_phone, R.id.ll_wx, R.id.ll_zy, R.id.ll_shop, R.id.ll_enter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_image:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //未授权，申请授权(从相册选择图片需要读取存储卡的权限)
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, RC_CHOOSE_PHOTO);
                } else {
                    //已授权，获取照片
                    //  choosePhoto();
                    PictureSelector.create(UserMessageActivity.this)
                            .openGallery(PictureMimeType.ofImage())
                            .selectionMode(PictureConfig.SINGLE)
                            .loadImageEngine(GlideEngine.createGlideEngine())
                            .forResult(PictureConfig.CHOOSE_REQUEST);
                }
                break;
            case R.id.ll_name:
                startActivity(new Intent(UserMessageActivity.this, UpdateNameActivity.class));
                break;
            case R.id.ll_phone:
                break;
            case R.id.ll_wx:

                startActivity(new Intent(UserMessageActivity.this, WxImageActivity.class)
                        .putExtra("wximg", myUserInfoBean.getData().getWxEwm() + "")
                        .putExtra("wxid", myUserInfoBean.getData().getWxEwmId() + ""));

                break;
            case R.id.ll_zy:

                break;
            case R.id.ll_shop:
                break;
            case R.id.ll_enter:
                break;
        }
    }

    /**
     * 图片回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    Log.i("TAG", "onActivityResult: 图片地址 ： " + new Gson().toJson(selectList));
                    if (selectList != null && selectList.size() != 0) {
                        //图片压缩
                        PictureUtils pictureUtils = new PictureUtils();
                        Bitmap bitmap = pictureUtils.getimage(selectList.get(0).getRealPath());
                        //获取文件类型
                        int i = selectList.get(0).getRealPath().lastIndexOf(".");
                        String s = selectList.get(0).getRealPath().substring(i, selectList.get(0).getRealPath().length());
                        String mitls = Calendar.getInstance().getTimeInMillis() + s;
                        String path = TAKE_PHOTO_PATH + "/" + mitls;
                        String mitl = path.substring(path.length() - 17);

                        try {
                            pictureUtils.saveBitmap(bitmap, path, 1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        String img = ImageLoadUtrils.imageToBase64(path);
                        HashMap<String, String> hashMap = new HashMap<String, String>();
                        hashMap.put("shard", "data:image/jpg;base64," + img);
                        hashMap.put("fileUsage", "BP");
                        hashMap.put("name", mitl);//文件名
                        hashMap.put("suffix", s);//后缀
                        hashMap.put("fileSize", selectList.get(0).getSize() + "");//文件大小
                        hashMap.put("shardKey", selectList.get(0).getId() + "");//分片主键
                        loading_view.show();
                        OkHttpUtils.postString()
                                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                                .addHeader("Content-Type", "application/json")
                                .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                                .url(Urls.loadimage)
                                .content(new Gson().toJson(hashMap))
                                .build().execute(new StringCallbacks() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                loading_view.dismiss();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                ImageLoadBean baseEntity = new Gson().fromJson(response, ImageLoadBean.class);
                                if (baseEntity.getCode() == 0) {
                                    filePath = baseEntity.getData().getFilePath();
                                    loading_view.dismiss();
                                 initokhttps(baseEntity.getData().getFileId());

                                    Glide.with(UserMessageActivity.this).load(filePath).into(userHerderImage);
                                } else {
                                    loading_view.dismiss();
                                    //     ToastUtil.showToast(WxImageActivity.this, "" + baseEntity.getMsg());
                                }
                            }
                        });


                    }
                    break;

            }
        }
    }
     //上传图片
    private void initokhttps(String fileId) {
        OkHttpUtils.get().url(Urls.headerimg)
                .addHeader("Content-Type","application/json")
                .addHeader("Authorization","Bearer "+ SharedPreferenceUtil.getStringData("token"))
                .addParams("avatar",fileId)
                .build().execute(new StringCallbacks() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                WxImagesBean baseEntity = new Gson().fromJson(response,WxImagesBean.class);
              if (baseEntity.getCode()==0){
                  ToastUtil.showToast(UserMessageActivity.this,"更新头像成功");
              }else {
                  ToastUtil.showToast(UserMessageActivity.this,"更新头像失败");
              }
            }
        });
    }
}